import { BaseResponse } from '@/api/index'
import { SelectRow, Page, ResSearch, Column, ResPageList, OpButton } from '@/types/common/page'
import { useState } from 'react'

export interface apiType<T, U = {}> {
  list: (param: Partial<Page | (Page & T) | U>) => Promise<BaseResponse<ResPageList<T>>>
  search: ResSearch
  add?: (param: Partial<T>) => Promise<BaseResponse<void>>
  update?: (param: Partial<T>) => Promise<BaseResponse<void>>
  delete?: (param: Partial<T>) => Promise<BaseResponse<void>>
}
/**
 *  P 主键类型
 *  T 表示表格列表字段类型
 *  U 表示查询类型
 */
export type UsePageList = <P, T, U>(
  api: apiType<T, U>,
  IDString: keyof T,
) => {
  IDString: keyof T
  rowlist: Array<{ row: T; op_group: Array<OpButton> }>
  searchParam: Partial<Page | Partial<T & Page> | U>
  columnlist: Array<Partial<Column>>
  searchList: ResSearch
  paging: Page
  setSizeChange: (current: number, pageSize: number) => Promise<void>
  loadTable: (param: Partial<Page | Partial<T & Page>>) => Promise<BaseResponse<ResPageList<T>>>
  getResData: () => ResPageList<T> | null
  tableLoading: boolean
}

/**
 *
 * @returns 增删改查hooks
 */
export const useBasePageList: UsePageList = <P, T, U = {}>(
  api: apiType<T, U>,
  IDString: keyof T,
) => {
  const [resData, setResData] = useState(null as ResPageList<T> | null)
  const [searchList, setSearchList] = useState([] as ResSearch)
  const [rowlist, setRowlist] = useState([] as Array<{ row: T; op_group: Array<OpButton> }>)
  const [columnlist, setColumnlist] = useState([] as Array<Column>)
  const [paging, setPaging] = useState({ page: 1, pageSize: 10 } as Page)
  const [searchParam, setSearchParam] = useState({ page: 1, pageSize: 10 } as Partial<
    Page | Partial<T & Page> | U
  >)
  const [tableLoading, setTableLoading] = useState(true)

  // 加载table
  const loadTable = async (param: Partial<Page | Partial<T & Page>>) => {
    const searchParamTmp: Partial<Page | Partial<T & Page>> = {}
    Object.keys(param).forEach((key) => {
      searchParamTmp[key as keyof Partial<Page | Partial<T & Page>>] =
        param[key as keyof Partial<Page | Partial<T & Page>>]
    })
    setSearchParam(searchParamTmp)
    setTableLoading(true)
    let res
    try {
      res = await api.list({ ...searchParam })
    } finally {
      setTableLoading(false)
    }
    return res
  }
  // 分页状态
  const setSizeChange = async (current: number, pageSize: number) => {
    setSearchParam({ page: current, pageSize: pageSize })

    const data = (await loadTable(searchParam)).data
    const { datas, page } = data
    setResData(data as ResPageList<T> | null)
    setPaging({ page: current, pageSize: pageSize, total: page.total })
    setRowlist(datas)
  }

  const getResData = () => {
    return resData
  }
  return {
    IDString,
    rowlist,
    searchParam,
    columnlist,
    searchList,
    getResData,
    paging,
    setSizeChange,
    loadTable,
    tableLoading,
  }
}
